package ltd.zouzheng.myutils.spring.rest;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * RestTemplate扩展
 *
 * @author zouzheng
 * @date 2021/4/13
 */
public class RestTemplateExt {

    private RestTemplate restTemplate;

    private RestTemplateExt() {
    }

    public RestTemplateExt(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public <T> T postForForm(String url, MultiValueMap<String, String> request, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> _request = new HttpEntity<>(request, headers);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, _request, responseType);
        return responseEntity.getBody();
    }

    public <T> T postForForm(String url, MultiValueMap<String, String> request, Class<T> responseType, Map<String, ?> uriVariables) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> _request = new HttpEntity<>(request, headers);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, _request, responseType, uriVariables);
        return responseEntity.getBody();
    }

    public <T> T postForObject(String url, Object request, Class<T> responseType) {
        return restTemplate.postForObject(url, request, responseType);
    }

    public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables) {
        return restTemplate.postForObject(url, request, responseType, uriVariables);
    }

    public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) {
        return restTemplate.postForObject(url, request, responseType, uriVariables);
    }

    public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables){
        return restTemplate.getForObject(url, responseType, uriVariables);
    }

    public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables){
        return restTemplate.getForObject(url, responseType, uriVariables);
    }

    public <T> T getForObject(String url, Class<T> responseType){
        return restTemplate.getForObject(url, responseType);
    }
}
